package com.desire.typeHandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

/**
 * @author LittleDesire
 * @description
 * @date 2022-04-29 周五 11:43
 * @since 17
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class ListVarcharTypeHandler extends BaseTypeHandler<List<String>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> list, JdbcType jdbcType) throws SQLException {
        System.out.println("转换ing...");
        StringBuffer sb = new StringBuffer();
        String msg = null;
        if (list != null) {
            for (String s : list) {
                sb.append(s).append(";");
            }
            msg = sb.toString();
            msg = msg.substring(0, msg.length() - 1);
        }
        ps.setString(i,msg);
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 根据结果集获取列名的值并且一 ； 分割开转化成一个集合
        return Arrays.asList(rs.getString(columnName).split(";"));
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return Arrays.asList(rs.getString(columnIndex).split(";"));
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return Arrays.asList(cs.getString(columnIndex).split(";"));
    }
}
